package com.xw.unification.entity;

import com.xw.unification.constant.UnificationConstant;
import static com.xw.unification.constant.UnificationConstant.DEFAULT_ERROR_STATUS;
import com.xw.unification.interfaces.UnifiedExceptionResolvable;
import lombok.Getter;
import lombok.Setter;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;

@Getter
@Setter
public class ErrorBody {

    private Date timestamp = new Date();
    private Integer status = DEFAULT_ERROR_STATUS.value();
    private String error;
    private String message;
    private String path;

    public ErrorBody(HttpServletRequest request, Exception exception) {
        this(request, DEFAULT_ERROR_STATUS.value(), exception);
    }

    public ErrorBody(HttpServletRequest request, Exception exception, String message) {
        this(request, DEFAULT_ERROR_STATUS.value(), exception, message);
    }

    public ErrorBody(HttpServletRequest request, UnifiedExceptionResolvable exception) {
        this.status = exception == null ? DEFAULT_ERROR_STATUS.value() : exception.getErrorCode();
        this.error = exception == null ? DEFAULT_ERROR_STATUS.getReasonPhrase() :
                Optional.ofNullable(exception.getErrorMessage())
                        .orElse(DEFAULT_ERROR_STATUS.getReasonPhrase());
        this.message = "";
        this.path = request == null ? "" : request.getRequestURI();
    }

    public ErrorBody(HttpServletRequest request, UnifiedExceptionResolvable exception, String message) {
        this.status = exception == null ? DEFAULT_ERROR_STATUS.value() : exception.getErrorCode();
        this.error = exception == null ? DEFAULT_ERROR_STATUS.getReasonPhrase() :
                Optional.ofNullable(exception.getErrorMessage())
                        .orElse(DEFAULT_ERROR_STATUS.getReasonPhrase());
        this.message = Optional.ofNullable(message).orElse("");
        this.path = request == null ? "" : request.getRequestURI();
    }

    public ErrorBody(HttpServletRequest request, Integer errorCode, Exception exception) {
        this.status = errorCode;
        this.error = exception == null ? DEFAULT_ERROR_STATUS.getReasonPhrase() :
                Optional.ofNullable(exception.getMessage())
                        .orElse(DEFAULT_ERROR_STATUS.getReasonPhrase());
        this.message = "";
        this.path = request == null ? "" : request.getRequestURI();
    }

    public ErrorBody(HttpServletRequest request, Integer errorCode, Exception exception, String message) {
        this.status = errorCode;
        this.error = exception == null ? DEFAULT_ERROR_STATUS.getReasonPhrase() :
                Optional.ofNullable(exception.getMessage())
                        .orElse(DEFAULT_ERROR_STATUS.getReasonPhrase());
        this.message = Optional.ofNullable(message).orElse("");
        this.path = request == null ? "" : request.getRequestURI();
    }

}